/**
 * MathMl to Latex Or Image
 */

const http = require("http");
const MathML2LaTeX = require("mathml2latex");
const MathML2LaTeX1 = require('mathml-to-latex');
const OSS = require('ali-oss');
const mjAPI = require("mathjax-node-svg2png");

const server = http.createServer((req, res) => {
    if (req.method === "POST" && req.headers["content-type"] === "application/json") {
        let body = "";
        req.on("data", (chunk) => {
            body += chunk.toString();
        });
        req.on("end", async () => {
            const data = JSON.parse(body);
            let resBody = {
                success: false,
            };

            if (typeof data == "object" && data.math) {
                console.log(data.math);
                // 需要latex公式
                if (req.url === "/toLatex") {
                    try {
                        // let latex = MathML2LaTeX.convert(data.math);
                        let latex = MathML2LaTeX1.convert(data.math);
                        latex = latex.replace('\\left{', '\\left\\{')
                        latex = latex.replace('}\\right', '}\\right.')
                        if (latex !== "") {
                            resBody.success = true;
                            // resBody.data = "$$" + latex + "$$";
                            resBody.data = latex;
                            console.log(latex);
                        }
                    } catch (error) {}
                }
                // 需要图片
                else if (req.url === "/toPng") {
                    try {
                        const mjAPI = require("mathjax-node-svg2png");
                        mjAPI.config({
                            MathJax: {},
                        });
                        mjAPI.start();

                        const result = await mjAPI.typeset({
                            math: data.math,
                            format: "MathML",
                            png: true,
                            scale: 2
                        });
                        if (!result.errors) {
                            resBody.success = true;
                            // resBody.data = result.png;

                            // 将图片保存到服务器然后直接返回路径
                            let imgPath = await upload(result.png)
                            resBody.data = imgPath ?? data.math;
                        }
                    } catch (error) {}
                }
                // latex 转 图片
                else if (req.url === "/latex2png") {
                    try {
                        let format = data.format ?? "TeX"
                        let path = data.path ?? ""

                        const mjAPI = require("mathjax-node-svg2png");
                        mjAPI.config({
                            MathJax: {},
                        });
                        mjAPI.start();

                        let math = data.math;
                        if (format === 'TeX') math = math.replace(/\\/g, '');
                        if (format === 'inline-TeX') math = math.replace(/^\$|\$$/g, '');

                        let scale = 1.5
                        if (math.indexOf("\\\\") !== -1) {
                            scale = 1
                        }

                        const result = await mjAPI.typeset({
                            math: math,
                            format: format,
                            png: true,
                            scale
                        });
                        if (!result.errors) {
                            resBody.success = true;

                            // 将图片保存到服务器然后直接返回路径
                            let imgPath = await upload(result.png, path)
                            resBody.data = imgPath ?? data.math;
                        }
                    } catch (error) {}
                }
                // 服务器状态检测
                else {
                    resBody.success = true;
                }
            }
            res.end(JSON.stringify(resBody));
        });
    } else {
        res.end("Hello World");
    }
});


function generateRandomName() {
    const timestamp = new Date().getTime(); // 获取当前时间戳
    const random = Math.floor(Math.random() * 1000); // 生成 0 到 999 的随机数
    return `${timestamp}_${random}`; // 拼接时间戳和随机数作为文件名
}

async function upload(base64File, path) {
    const base64DataArray = base64File.split(',');
    const imageData = base64DataArray[1];
    const decodedImage = Buffer.from(imageData, 'base64');

    // 配置OSS客户端
    const client = new OSS({
        region: 'oss-cn-qingdao',
        accessKeyId: 'LTAIDtW6z6xcmXBZ',
        accessKeySecret: 'GQHIRmbYqirN4kMACgc2h91CCmM1wh',
        bucket: 'tikuimgs',
        endpoint: 'oss-cn-qingdao.aliyuncs.com',
    });

    let filename = generateRandomName();
    filename+='.png';

    if (path) {
        if (!/^\/.*\/$/.test(path)) {
            path = '/' + path.replace(/^\/*/, '').replace(/\/*$/, '') + '/';
        }
    }

    let filepath = (path ?? '/tikuimg/paper/')+filename

    // 上传文件到阿里云OSS
    try {
        // 上传文件
        const result = await client.put(filepath, decodedImage);
        if (result.res.status === 200 && result.res.statusMessage === 'OK') {
            return '/'+result.name
        }else {
            return null
        }
    } catch (err) {
        console.log('[ALI OSS ERROR]', err);
        return null
    }
}

server.listen(
    {
        host: "0.0.0.0",
        port: 6666,
    },
    () => {
        console.log("服务已运行到[6666]端口");
    }
);
